package com.jtf.web.link.jfx;

import com.jtf.web.link.application.BaiduPcApplication;
import com.jtf.web.link.application.BaseApplication;
import com.jtf.web.link.domain.entity.UrlEntity;
import com.jtf.web.link.domain.entity.UrlRepository;
import de.felixroske.jfxsupport.AbstractFxmlView;
import de.felixroske.jfxsupport.FXMLController;
import de.felixroske.jfxsupport.FXMLView;
import de.felixroske.jfxsupport.GUIState;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventType;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.ResourceBundle;

@FXMLView()
@FXMLController
@Data
public class MainView extends AbstractFxmlView implements Initializable {

    @Autowired
    protected UrlRepository urlRepository;

    // root
    @FXML
    protected Pane context;

    // 搜索单选
    @FXML
    protected ToggleGroup toggleGroup ;

    // 记录
    @FXML
    protected TableView tableView;

    // 新增按钮
    @FXML
    protected Button addButton;

    @FXML
    protected Button deleteButton;
    @FXML
    protected Button testButton;
    @FXML
    protected Button testEndButton;

    /**
     * 关键字输入
     */
    @FXML
    protected TextField keyWordsTextField;

    /**
     * 关键字输入
     */
    @FXML
    protected TextField urlTextField;


    protected UrlEntity urlEntity;

//    在Java启动时加入-Djdk.gtk.version=2即可。即可  中文输入问题

//    javax.net.ssl.SSLException: No PSK available. Unable to resume.resume
//    wait for the release of JDK 12
//    or for a backport to JDK 11
//    or use this command line parameter as a workaround: -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2


//    @FXML
//    protected ObjectProperty<EventHandler<ActionEvent>> addButtonAction;

    public MainView() {
//        addButtonAction = new SimpleObjectProperty<EventHandler<ActionEvent>>((event -> {
//            System.out.println(event);
//            System.out.println(toggleGroup.getUserData());
//        })) ;
    }
    static class XCell extends TableCell<String, String> {
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            this.setText(item);
            this.setTooltip(
                    (empty || item==null) ? null : new Tooltip(item));
        }
    }

    // 设置新增
    protected void editable(){
        for (Toggle toggle : toggleGroup.getToggles()) {
            RadioButton radioButton = (RadioButton) toggle;
            radioButton.setDisable(false);
            radioButton.setSelected(false);
        }
        urlTextField.setEditable(true);
        urlTextField.setText("");
        keyWordsTextField.setEditable(true);
        keyWordsTextField.setText("");
        addButton.setText("保存");
    }

    // 新增数据
    protected void addData(){
        Toggle selectedToggle = toggleGroup.getSelectedToggle();
        if(selectedToggle == null){
            addDialog("请选择搜索引擎");
            return;
        }
        String engine = ((RadioButton) selectedToggle).getText();
        String keywords = keyWordsTextField.getText();
        if(!StringUtils.hasText(keywords)){
            addDialog("请输入关键字");
            return;
        }
        String url = urlTextField.getText();
        if(!StringUtils.hasText(url)){
            addDialog("请输入url");
            return;
        }
        try {
           new URL(url);
        } catch (MalformedURLException e) {
            addDialog("请输入正确的url");
            return;
        }
        initUrlDataSetting();
        addButton.setText("新增");
        UrlEntity urlEntity = new UrlEntity();
        urlEntity.setUrl(url);
        urlEntity.setEngine(engine);
        urlEntity.setKeywords(keywords);
        urlEntity.setUpdateDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        urlEntity.setContent("");
        urlRepository.save(urlEntity);
        flushTableData();

    }

    protected void flushTableData(){
        List<UrlEntity> list = urlRepository.findAll(Sort.by(Sort.Direction.DESC, "id"));
        tableView.setItems(FXCollections.observableArrayList(list));
    }

    // 新增按钮点击
    public void addButtonAction(ActionEvent event){
        String text = addButton.getText();
        if(text.equals("新增")){
            editable();
        }else{
            addData();
        }
    }

    public void deleteButtonAction(ActionEvent event){
        if(this.urlEntity == null){
            this.addDialog("请先选择行");
            return;
        }
        this.urlRepository.delete(this.urlEntity);
        this.flushTableData();
        this.urlEntity = null;
        initUrlDataSetting();
        deleteButton.setDisable(true);
    }
    public void testButtonAction(ActionEvent event){
        BaiduPcApplication secondStage = new BaiduPcApplication("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36",
        this.urlEntity.getKeywords(), this.urlEntity.getUrl());

        secondStage.test();
        this.testEndButton.setDisable(false);
        this.testButton.setDisable(true);
    }
    public void testEndButtonAction(ActionEvent event){
        this.testEndButton.setDisable(true);
        this.testButton.setDisable(false);
    }

    private void addDialog(String info){
        Alert _alert = new Alert(Alert.AlertType.WARNING);
        _alert.setContentText(info);
        _alert.initOwner(GUIState.getStage());
        _alert.show();

    }



    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        initTableViewSetting();
        flushTableData();
        initUrlDataSetting();
        deleteButton.setDisable(true);
    }


    /**
     * 初始化urlData设置
     */
    private void initUrlDataSetting(){
        for (Toggle toggle : toggleGroup.getToggles()) {
            RadioButton radioButton = (RadioButton) toggle;
            radioButton.setDisable(true);
            radioButton.setSelected(false);
        }
        urlTextField.setEditable(false);
        urlTextField.setText("");
        keyWordsTextField.setEditable(false);
        keyWordsTextField.setText("");
        addButton.setText("新增");
        deleteButton.setDisable(true);
        testButton.setDisable(true);
        testEndButton.setDisable(true);
    }
    /**
     * 初始化表格设置
     */
    private void initTableViewSetting(){
        ObservableList columns = tableView.getColumns();
        for (Object column : columns) {
            TableColumn c= (TableColumn) column;
            if(c.getText().equals("#")){
                c.setCellValueFactory(new PropertyValueFactory<UrlEntity, String>("id"));

            }
            else if(c.getText().equals("搜索引擎")){
                c.setCellValueFactory(new PropertyValueFactory<UrlEntity, String>("engine"));
                c.setCellFactory((tableColumn)->new XCell());
            }
            else if(c.getText().equals("关键字")){
                c.setCellValueFactory(new PropertyValueFactory<UrlEntity, String>("keywords"));
                c.setCellFactory((tableColumn)->new XCell());
            }
            else if(c.getText().equals("网址")){
                c.setCellValueFactory(new PropertyValueFactory<UrlEntity, String>("url"));
                c.setCellFactory((tableColumn)->new XCell());
            }
            else if(c.getText().equals("内容")){
                c.setCellValueFactory(new PropertyValueFactory<UrlEntity, String>("content"));
                c.setCellFactory((tableColumn)->new XCell());
            }
            else if(c.getText().equals("时间")){
                c.setCellValueFactory(new PropertyValueFactory<UrlEntity, String>("updateDate"));
                c.setCellFactory((tableColumn)->new XCell());
            }

        }
        tableView.getSelectionModel().selectedItemProperty()
                .addListener(new TableViewSelectListener() );
    }

    // 表格选中监听器
    class TableViewSelectListener implements ChangeListener<UrlEntity>{
        @Override
        public void changed(ObservableValue<? extends UrlEntity> observable, UrlEntity oldValue, UrlEntity newValue) {
            if(newValue != null){
                urlEntity = newValue;
                initUrlDataSetting();
                ObservableList<Toggle> toggles = toggleGroup.getToggles();
                for (Toggle toggle : toggles) {
                    RadioButton button = (RadioButton) toggle;
                    if(button.getText().equals(urlEntity.getEngine())){
                        button.setSelected(true);
                        break;
                    }
                }
                keyWordsTextField.setText(urlEntity.getKeywords());
                urlTextField.setText(urlEntity.getUrl());
                deleteButton.setDisable(false);
                testButton.setDisable(false);
            }else {
                urlEntity = null;

            }
        }
    }
}
